<template>
  <el-container style="height: 950px; border: 1px solid #eee">
    <!-- 左侧患者选择区 -->
    <el-aside width="350px">
      <el-container>
        <!-- 患者选择头部 -->
        <el-header style="padding: 0; margin: 0">
          <el-row>
            <el-col :span="21" style="text-align: left">
              <el-tag>我的患者：</el-tag>
            </el-col>
            <el-col :span="3" style="text-align: right">
              <el-button
                  type="primary"
                  size="small"
                  @click="reloadUser"
                  style="margin-right: 5px"
                  title="刷新患者列表"
              >
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-input
                placeholder="请输入患者姓名搜索"
                v-model="inputPatient"
                style="width: 100%"
                @keyup.enter="searchPatient"
            >
              <template #prepend>患者名：</template>
              <template #append>
                <el-icon @click="searchPatient"><Search /></el-icon>
              </template>
            </el-input>
          </el-row>
        </el-header>

        <!-- 患者列表内容区 -->
        <el-main style="height: 800px; padding: 0; margin: 0">
          <el-tabs type="border-card">
            <!-- 我的患者标签页 -->
            <el-tab-pane label="我的患者">
              <el-tag size="small">未诊患者：</el-tag>
              <el-table
                  :data="myUnvisitedPatients"
                  highlight-current-row
                  @row-click="handlePatientSelect"
                  style="width: 100%"
                  :show-header="false"
                  max-height="300"
                  size="small"
                  empty-text="暂无未诊患者"
              >
                <el-table-column property="registerId" label="挂号ID" width="80"></el-table-column>
                <el-table-column property="caseNumber" label="病历号" width="80"></el-table-column>
                <el-table-column property="realName" label="姓名"></el-table-column>
                <el-table-column property="age" label="年龄" width="50"></el-table-column>
              </el-table>

              <br />

              <el-tag size="small">已诊患者：</el-tag>
              <el-table
                  :data="myVisitedPatients"
                  @row-click="handlePatientSelect"
                  @row-dblclick="handlePatientDblClick"
                  style="width: 100%"
                  :show-header="false"
                  max-height="300"
                  size="small"
                  empty-text="暂无已诊患者"
              >
                <el-table-column property="registerId" label="挂号ID" width="80"></el-table-column>
                <el-table-column property="caseNumber" label="病历号" width="80"></el-table-column>
                <el-table-column property="realName" label="姓名"></el-table-column>
                <el-table-column property="age" label="年龄" width="50"></el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-main>
      </el-container>
    </el-aside>

    <!-- 右侧门诊功能区 -->
    <el-container direction="vertical" style="height: 950px">
      <el-row style="margin: 10px 0;">
        <span style="margin-left: 20px; font-size: small;">
          <!-- 修复：增强空值判断和默认值显示 -->
          {{ currentPatient ?
            `当前患者：${currentPatient.realName || '未知姓名'}（挂号ID：${currentPatient.registerId || '未知ID'}）` :
            '请从左侧列表选择患者'
          }}
        </span>
        <el-button
            type="link"
            size="small"
            style="float: right; margin-right: 20px;"
            @click="endRegister"
            v-if="currentPatient && currentPatient.visitState === 0"
        >
          诊毕
        </el-button>
      </el-row>

      <!-- 门诊主要功能标签页 -->
      <el-tabs type="border-card" :before-leave="toTab">
        <!-- 病历首页标签页 -->
        <el-tab-pane label="病历首页">
          <el-container v-loading="loading">
            <el-main style="width:100%; background:#fff; height:800px; overflow-y: auto; padding: 10px;">
              <el-form
                  ref="form"
                  :model="medicalRecord01"
                  label-width="80px"
                  label-position="left"
                  size="small"
              >
                <el-row style="background-color: #EAF1F5; padding: 5px 0; margin-bottom: 10px;">
                  <el-col :span="8"></el-col>
                  <el-col :span="4"><el-button type="link" size="small" @click="stageCheck">暂存</el-button></el-col>
                  <el-col :span="4"><el-button type="link" size="small" @click="saveCheck">提交</el-button></el-col>
                  <el-col :span="4"><el-button type="link" size="small" :disabled="isSaved" @click="cleanCheck">清空所有</el-button></el-col>
                  <el-col :span="4"><el-button type="link" size="small" @click="refMedicalRecord">刷新</el-button></el-col>
                </el-row>

                <el-tag style="margin-bottom: 10px;">病史内容：</el-tag>

                <el-form-item label="主诉">
                  <el-input type="textarea" :rows="1" v-model="medicalRecord01.readme" :disabled="isSaved"></el-input>
                </el-form-item>

                <el-form-item label="现病史">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.present" :disabled="isSaved"></el-input>
                </el-form-item>

                <el-form-item label="诊断">
                  <el-input type="textarea" :rows="2" v-model="medicalRecord01.diagnosis" :disabled="isSaved"></el-input>
                </el-form-item>

                <el-form-item style="margin-top: 20px;">
                  <el-button type="primary" @click="saveCheck" :disabled="isSaved">提交病历</el-button>
                  <el-button type="link" @click="stageCheck" style="margin-left: 10px;">暂存</el-button>
                </el-form-item>
              </el-form>
            </el-main>
          </el-container>
        </el-tab-pane>

        <!-- 检验申请标签页 -->
        <el-tab-pane label="检验申请" :lazy="true">
          <div>
            <el-dialog
                title="新增检验申请"
                :visible.sync="dialog01Visible"
                width="30%"
            >
              <el-form size="small">
                <el-form-item>
                  <el-input
                      placeholder="请输入检验名称搜索"
                      style="width: 100%"
                      v-model="testName"
                      @keyup.enter="searchTestItems"
                  >
                    <template #prepend>检验名称：</template>
                    <el-button #append @click="searchTestItems"><Search /></el-button>
                  </el-input>
                </el-form-item>

                <el-form-item>
                  <el-table
                      border
                      :data="testItems"
                      size="small"
                      @row-click="selectTestItem"
                      highlight-current-row
                  >
                    <el-table-column type="selection" width="40"></el-table-column>
                    <el-table-column property="feilei" label="分类" width="80"></el-table-column>
                    <el-table-column property="position" label="项目"></el-table-column>
                  </el-table>
                </el-form-item>

                <el-form-item label="检验科室">
                  <el-select v-model="selectedDept" placeholder="请选择">
                    <el-option
                        v-for="item in deptList"
                        :key="item.id"
                        :label="item.deptname"
                        :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item label="是否加急：">
                  <el-switch
                      v-model="isUrgent"
                      active-color="#13ce66"
                  ></el-switch>
                </el-form-item>

                <el-form-item>
                  <el-button type="primary" @click="confirmAddTest">确 定</el-button>
                  <el-button @click="dialog01Visible = false">取 消</el-button>
                </el-form-item>
              </el-form>
            </el-dialog>

            <el-container direction="horizontal">
              <el-aside style="width: 700px; height: 500px;">
                <el-row style="background-color: #EAF1F5; padding: 5px 0;">
                  <el-col :span="8" style="margin-top: 4px;">
                    <el-tag size="small">本项目金额合计：</el-tag>
                    <el-tag type="warning" size="small">{{ totalAmount.toFixed(2) }}元</el-tag>
                  </el-col>
                  <el-col :span="3"><el-button type="link" size="small" @click="dialog01Visible=true">新增项目</el-button></el-col>
                  <el-col :span="3"><el-button type="link" size="small" @click="deleteTestItems">删除项目</el-button></el-col>
                  <el-col :span="2"><el-button type="link" size="small" @click="submitTestItems">开立</el-button></el-col>
                </el-row>

                <el-form ref="testForm" label-width="80px">
                  <el-row>
                    <el-col :span="22" style="margin-top: 4px;">
                      <el-table
                          ref="testTable"
                          :data="selectedTestItems"
                          style="width: 100%; margin: 0px; padding: 0px;"
                          :show-header="true"
                          size="small"
                          @selection-change="handleTestSelectionChange"
                      >
                        <el-table-column type="selection" width="40"></el-table-column>
                        <el-table-column property="feilei" label="分类" width="80"></el-table-column>
                        <el-table-column property="position" label="项目"></el-table-column>
                        <el-table-column property="keshi" label="执行科室" width="80"></el-table-column>
                        <el-table-column property="jiaji" label="加急" width="50">
                          <template #default="scope">{{ scope.row.jiaji ? '是' : '否' }}</template>
                        </el-table-column>
                        <el-table-column property="zhuangtai" label="状态" width="80"></el-table-column>
                        <el-table-column property="danjia" label="单价" width="80"></el-table-column>
                      </el-table>
                    </el-col>
                  </el-row>

                  <el-row style="margin-top: 10px;">
                    <el-form-item label="目的要求">
                      <el-input
                          type="textarea"
                          :rows="4"
                          placeholder="请输入检验目的和要求"
                          v-model="testPurpose"
                      ></el-input>
                    </el-form-item>
                  </el-row>
                </el-form>
              </el-aside>
            </el-container>
          </div>
        </el-tab-pane>

        <!-- 门诊确诊标签页 -->
        <el-tab-pane label="门诊确诊" :lazy="true">
          <el-container v-loading="diagnosisLoading">
            <el-main style="width:100%; background:#fff; height:800px; overflow-y: auto; padding: 10px;">
              <el-form
                  ref="diagnosisForm"
                  :model="diagnosisInfo"
                  label-width="80px"
                  label-position="left"
                  size="small"
              >
                <el-row style="background-color: #EAF1F5; padding: 5px 0; margin-bottom: 10px;">
                  <el-col :span="12"></el-col>
                  <el-col :span="6"><el-button type="link" size="small" @click="saveDiagnosis">保存诊断</el-button></el-col>
                  <el-col :span="6"><el-button type="link" size="small" @click="confirmDiagnosis">确认诊断</el-button></el-col>
                </el-row>

                <el-tag style="margin-bottom: 10px;">诊断信息：</el-tag>

                <!-- 主要诊断 -->
                <el-form-item label="主要诊断" required>
                  <el-input
                      v-model="diagnosisInfo.mainDiagnosis"
                      placeholder="请输入主要诊断"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 诊断编码 -->
                <el-form-item label="诊断编码">
                  <el-input
                      v-model="diagnosisInfo.diagnosisCode"
                      placeholder="请输入ICD编码"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 次要诊断 -->
                <el-form-item label="次要诊断">
                  <el-input
                      type="textarea"
                      :rows="2"
                      v-model="diagnosisInfo.secondaryDiagnosis"
                      placeholder="请输入次要诊断，多个诊断用分号分隔"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 诊断依据 -->
                <el-form-item label="诊断依据">
                  <el-input
                      type="textarea"
                      :rows="3"
                      v-model="diagnosisInfo.diagnosisBasis"
                      placeholder="请输入诊断依据"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 治疗方案 -->
                <el-form-item label="治疗方案">
                  <el-input
                      type="textarea"
                      :rows="4"
                      v-model="diagnosisInfo.treatmentPlan"
                      placeholder="请输入治疗方案"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 医嘱 -->
                <el-form-item label="医嘱">
                  <el-input
                      type="textarea"
                      :rows="3"
                      v-model="diagnosisInfo.medicalAdvice"
                      placeholder="请输入医嘱"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <!-- 复诊安排 -->
                <el-form-item label="复诊安排">
                  <el-select
                      v-model="diagnosisInfo.followUpVisit"
                      placeholder="请选择复诊安排"
                      :disabled="diagnosisConfirmed"
                  >
                    <el-option label="无需复诊" value="none"></el-option>
                    <el-option label="1周后复诊" value="1week"></el-option>
                    <el-option label="2周后复诊" value="2weeks"></el-option>
                    <el-option label="1月后复诊" value="1month"></el-option>
                    <el-option label="3月后复诊" value="3months"></el-option>
                    <el-option label="其他" value="other"></el-option>
                  </el-select>
                </el-form-item>

                <!-- 其他说明 -->
                <el-form-item label="其他说明">
                  <el-input
                      type="textarea"
                      :rows="3"
                      v-model="diagnosisInfo.otherInstructions"
                      placeholder="请输入其他说明"
                      :disabled="diagnosisConfirmed"
                  ></el-input>
                </el-form-item>

                <el-form-item style="margin-top: 20px;">
                  <el-button
                      type="primary"
                      @click="confirmDiagnosis"
                      :disabled="diagnosisConfirmed"
                  >
                    确认诊断并提交
                  </el-button>
                  <el-button
                      type="default"
                      @click="saveDiagnosis"
                      style="margin-left: 10px;"
                      :disabled="diagnosisConfirmed"
                  >
                    保存暂存
                  </el-button>
                  <el-button
                      type="warning"
                      @click="resetDiagnosisForm"
                      style="margin-left: 10px;"
                      :disabled="diagnosisConfirmed"
                  >
                    重置
                  </el-button>
                </el-form-item>

                <!-- 诊断状态显示 -->
                <el-form-item v-if="diagnosisConfirmed">
                  <el-tag type="success" size="large">
                    该患者诊断已确认，诊断时间
                    {{ formatDateTime(diagnosisInfo.confirmedTime) || '未知' }}
                  </el-tag>
                </el-form-item>
              </el-form>
            </el-main>
          </el-container>
        </el-tab-pane>
      </el-tabs>
    </el-container>
  </el-container>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { ElNotification, ElMessageBox, ElLoading } from 'element-plus'
import service from '@/utils/request'
import { Search, Refresh } from "@element-plus/icons-vue";
import { useCounterStore } from "@/stores/counter.js";

// -------------------------- 数据定义 --------------------------
const counter = useCounterStore();
const userId = ref(1);

// 患者数据
const myUnvisitedPatients = ref([])  // 我的未诊患者
const myVisitedPatients = ref([])    // 我的已诊患者
const inputPatient = ref('')         // 患者搜索关键词
const currentPatient = ref(null)     // 当前选中患者

// 病历数据
const medicalRecord01 = ref({
  readme: '',
  present: '',
  diagnosis: '',
  caseNumber: '',
  caseState: 0 // 0-未保存 1-暂存 2-已提交
})
const loading = ref(false)
const isSaved = ref(false)

// 检验申请数据
const testItems = ref([])
const selectedTestItems = ref([])
const dialog01Visible = ref(false)
const testName = ref('')
const deptList = ref([])
const selectedDept = ref('')
const isUrgent = ref(false)
const testPurpose = ref('')
const totalAmount = ref(0)
const multipleSelection = ref([])

// 门诊确诊数据
const diagnosisInfo = ref({
  mainDiagnosis: '',         // 主要诊断
  diagnosisCode: '',         // 诊断编码
  secondaryDiagnosis: '',    // 次要诊断
  diagnosisBasis: '',        // 诊断依据
  treatmentPlan: '',         // 治疗方案
  medicalAdvice: '',         // 医嘱
  followUpVisit: '',         // 复诊安排
  otherInstructions: '',     // 其他说明
  caseNumber: '',            // 病历号
  confirmed: false,          // 是否确认
  confirmedTime: ''          // 确认时间
})
const diagnosisLoading = ref(false)
const diagnosisConfirmed = ref(false)  // 诊断是否已确认

// -------------------------- 工具函数 --------------------------
// 格式化日期时间
const formatDateTime = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// -------------------------- 生命周期钩子 --------------------------
onMounted(() => {
  // 监听userId变化，加载我的患者
  watch(
      () => userId.value,
      (newUserId) => {
        if (newUserId) {
          loadMyPatients(newUserId)
        }
      }
  )

  // 监听当前患者变化，加载对应数据
  watch(
      () => currentPatient.value,
      (newPatient) => {
        if (newPatient && newPatient.caseNumber) {
          // 验证患者数据完整性
          if (!newPatient.realName) ElNotification({
            title: '提示',
            message: '患者数据不完整（缺少姓名）',
            type: 'warning'
          })
          if (!newPatient.registerId) ElNotification({
            title: '提示',
            message: '患者数据不完整（缺少挂号ID）',
            type: 'warning'
          })

          loadMedicalRecord(newPatient.caseNumber)
          loadPatientTestItemsByRegisterId(newPatient.registerId)
          fetchDiagnosisInfo(newPatient.caseNumber)
        } else {
          resetDiagnosisForm()
        }
      }
  )

  // 初始加载数据
  if (userId.value) {
    loadMyPatients(userId.value)
  }
  loadDeptList()
  loadTestItems()
});

// -------------------------- 患者管理 --------------------------
// 加载我的患者列表
const loadMyPatients = async (doctorId) => {
  if (!doctorId) {
    ElNotification({
      title: '错误',
      message: '未获取到医生信息',
      type: 'error'
    })
    return
  }

  const loadingInstance = ElLoading.service({
    lock: true,
    text: '加载我的患者中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })

  try {
    const res = await service.get('/api/patients/doctor', {
      params: { doctorId }
    })

    // 验证返回数据结构
    if (res.data && Array.isArray(res.data.unvisited) && Array.isArray(res.data.visited)) {
      // 过滤并修复不完整的患者数据
      myUnvisitedPatients.value = res.data.unvisited.map(patient => ({
        realName: patient.realName || '未知姓名',
        registerId: patient.registerId || '未知ID',
        caseNumber: patient.caseNumber || '',
        age: patient.age || '',
        visitState: patient.visitState || 0,
        ...patient
      }))

      myVisitedPatients.value = res.data.visited.map(patient => ({
        realName: patient.realName || '未知姓名',
        registerId: patient.registerId || '未知ID',
        caseNumber: patient.caseNumber || '',
        age: patient.age || '',
        visitState: patient.visitState || 1,
        ...patient
      }))

      ElNotification({
        title: '成功',
        message: `加载我的患者，未诊${myUnvisitedPatients.value.length}人、已诊${myVisitedPatients.value.length}人`,
        type: 'success'
      })
    } else {
      throw new Error("患者数据格式错误：预期包含unvisited和visited数组")
    }
  } catch (error) {
    console.error('加载我的患者失败', error)
    ElNotification({
      title: '错误',
      message: '加载患者失败，请重试',
      type: 'error'
    })
    myUnvisitedPatients.value = []
    myVisitedPatients.value = []
  } finally {
    loadingInstance.close()
  }
}

// 搜索我的患者
const searchPatient = async () => {
  if (!userId.value) return;

  try {
    const res = await service.get('/api/patients/search', {
      params: {
        keyword: inputPatient.value.trim(),
        doctorId: userId.value
      }
    })

    if (res.data) {
      myUnvisitedPatients.value = res.data.unvisited.map(patient => ({
        realName: patient.realName || '未知姓名',
        registerId: patient.registerId || '未知ID',
        ...patient
      })) || []
      myVisitedPatients.value = res.data.visited.map(patient => ({
        realName: patient.realName || '未知姓名',
        registerId: patient.registerId || '未知ID',
        ...patient
      })) || []
    }
  } catch (error) {
    console.error('搜索患者失败', error)
    ElNotification({
      title: '错误',
      message: '搜索患者失败，请重试',
      type: 'error'
    })
  }
}

// 选择患者
const handlePatientSelect = (row) => {
  console.log("选中患者数据：", row) // 调试用
  if (!row) {
    ElNotification({
      title: '提示',
      message: '未获取到有效患者数据',
      type: 'warning'
    })
    return
  }
  currentPatient.value = row
}

// 双击已诊患者
const handlePatientDblClick = (row) => {
  handlePatientSelect(row)
}

// 刷新患者列表
const reloadUser = () => {
  inputPatient.value = ''
  if (userId.value) {
    loadMyPatients(userId.value)
  }
}

// 标记患者为已诊
const endRegister = async () => {
  if (!currentPatient.value) return

  try {
    const res = await service.put(`/api/patients/${currentPatient.value.id}/status`, {
      status: 'visited'
    })

    if (res.status === 200) {
      ElNotification({
        title: '成功',
        message: '已标记患者为已诊',
        type: 'success'
      })
      loadMyPatients(userId.value)
      currentPatient.value.visitState = 2
    }
  } catch (error) {
    console.error('标记患者为已诊失败', error)
    ElNotification({
      title: '错误',
      message: '操作失败，请重试',
      type: 'error'
    })
  }
}

// -------------------------- 病历管理功能 --------------------------
// 加载患者病历
// 1. 加载病历方法（loadMedicalRecord）
const loadMedicalRecord = async (casenumber) => { // 参数名改为casenumber
  if (!casenumber) {
    medicalRecord01.value = {
      readme: '',
      present: '',
      diagnosis: '',
      casenumber: '', // 改为casenumber
      casestate: 0    // 状态字段改为casestate（后端是casestate）
    }
    isSaved.value = false
    return
  }

  loading.value = true
  try {
    const res = await service.get('/api/medical-records', {
      params: { casenumber } // 传递casenumber
    })

    if (res.data) {
      medicalRecord01.value = res.data
      isSaved.value = res.data.casestate === 2 // 状态字段改为casestate
    } else {
      medicalRecord01.value = {
        readme: '',
        present: '',
        diagnosis: '',
        casenumber, // 改为casenumber
        casestate: 0 // 改为casestate
      }
      isSaved.value = false
    }
  } catch (error) {
    // 错误处理不变
  } finally {
    loading.value = false
  }
}

// 2. 暂存病历方法（stageCheck）
const stageCheck = async () => {
  if (!currentPatient.value) {
    // 提示不变
    return
  }

  try {
    const recordData = {
      ...medicalRecord01.value,
      casenumber: currentPatient.value.casenumber, // 改为casenumber（从患者信息获取）
      patientName: currentPatient.value.realName,
      doctorId: userId.value,
      casestate: 1 // 状态字段改为casestate（后端是casestate）
    }

    const res = await service.post('/api/medical-records/save', recordData)

    if (res.data) { // 后端返回的是实体对象，无需判断success
      ElNotification({
        title: '成功',
        message: '病历已暂存',
        type: 'success'
      })
      medicalRecord01.value.casestate = 1 // 改为casestate
    }
  } catch (error) {
    // 错误处理不变
  }
}

// 3. 提交病历方法（saveCheck）
const saveCheck = async () => {
  if (!currentPatient.value) {
    // 提示不变
    return
  }

  if (!medicalRecord01.value.diagnosis) {
    // 提示不变
    return
  }

  try {
    const recordData = {
      ...medicalRecord01.value,
      casenumber: currentPatient.value.casenumber, // 改为casenumber
      patientName: currentPatient.value.realName,
      doctorId: userId.value,
      casestate: 2 // 改为casestate
    }

    const res = await service.post('/api/medical-records/save', recordData)

    if (res.data) { // 后端返回实体对象，无需判断success
      ElNotification({
        title: '成功',
        message: '病历已提交',
        type: 'success'
      })
      medicalRecord01.value.casestate = 2 // 改为casestate
      isSaved.value = true
    }
  } catch (error) {
    // 错误处理不变
  }
}

// 4. 刷新病历方法（refMedicalRecord）
const refMedicalRecord = () => {
  if (currentPatient.value) {
    loadMedicalRecord(currentPatient.value.casenumber) // 改为casenumber
  }
}

// -------------------------- 检验申请功能 --------------------------
// 加载科室列表
const loadDeptList = async () => {
  try {
    const res = await service.get('/api/departments')
    deptList.value = res.data || []
  } catch (error) {
    console.error('加载科室列表失败', error)
  }
}

// 加载检验项目列表
const loadTestItems = async () => {
  try {
    const res = await service.get('/api/test-items')
    testItems.value = res.data || []
  } catch (error) {
    console.error('加载检验项目失败', error)
  }
}

// 搜索检验项目
const searchTestItems = async () => {
  try {
    const res = await service.get('/api/test-items/search', {
      params: { name: testName.value.trim() }
    })
    testItems.value = res.data || []
  } catch (error) {
    console.error('搜索检验项目失败', error)
  }
}

// 选择检验项目
const selectTestItem = (row) => {
  // 单选逻辑处理
}

// 确认添加检验项目
const confirmAddTest = () => {
  if (!selectedDept.value) {
    ElNotification({
      title: '提示',
      message: '请选择检验科室',
      type: 'warning'
    })
    return
  }

  const selection = multipleSelection.value
  if (selection.length === 0) {
    ElNotification({
      title: '提示',
      message: '请选择检验项目',
      type: 'warning'
    })
    return
  }

  // 处理选中项目，添加科室和加急信息
  const newItems = selection.map(item => ({
    ...item,
    keshi: deptList.value.find(d => d.id === selectedDept.value)?.deptname || '',
    jiaji: isUrgent.value,
    zhuangtai: '未执行',
    selectedDeptId: selectedDept.value
  }))

  // 添加到已选列表（去重）
  newItems.forEach(newItem => {
    const exists = selectedTestItems.value.some(
        item => item.id === newItem.id && item.selectedDeptId === newItem.selectedDeptId
    )
    if (!exists) {
      selectedTestItems.value.push(newItem)
    }
  })

  // 计算总金额
  calculateTotalAmount()

  // 关闭对话框
  dialog01Visible.value = false
  // 重置选择状态
  multipleSelection.value = []
  testName.value = ''
  selectedDept.value = ''
  isUrgent.value = false
}

// 处理检验项目选择变化
const handleTestSelectionChange = (val) => {
  multipleSelection.value = val
}

// 计算检验项目总金额
const calculateTotalAmount = () => {
  totalAmount.value = selectedTestItems.value.reduce((sum, item) => {
    return sum + (Number(item.danjia) || 0)
  }, 0)
}

// 删除选中的检验项目
const deleteTestItems = () => {
  if (multipleSelection.value.length === 0) {
    ElNotification({
      title: '提示',message: '请先选择要删除的检验项目',
      type: 'warning'
    })
    return
  }

  ElMessageBox.confirm(
      '确定要删除选中的检验项目吗？',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    // 过滤掉选中的项目
    selectedTestItems.value = selectedTestItems.value.filter(item =>
        !multipleSelection.value.some(selected => selected.id === item.id && selected.selectedDeptId === item.selectedDeptId)
    )
    // 重新计算总金额
    calculateTotalAmount()
    // 清空选择
    multipleSelection.value = []
    ElNotification({
      title: '成功',
      message: '检验项目已删除',
      type: 'success'
    })
  }).catch(() => {
    // 取消删除
  })
}

// 提交检验申请
const submitTestItems = async () => {
  if (!currentPatient.value) {
    ElNotification({
      title: '提示',
      message: '请先选择患者',
      type: 'warning'
    })
    return
  }

  if (selectedTestItems.value.length === 0) {
    ElNotification({
      title: '提示',
      message: '请先添加检验项目',
      type: 'warning'
    })
    return
  }

  try {
    const testData = {
      registerId: currentPatient.value.registerId,
      caseNumber: currentPatient.value.caseNumber,
      doctorId: userId.value,
      items: selectedTestItems.value,
      purpose: testPurpose.value
    }

    const res = await service.post('/api/test-applications', testData)

    if (res.data.success) {
      ElNotification({
        title: '成功',
        message: '检验申请已提交',
        type: 'success'
      })
      // 清空已选项目和目的要求
      selectedTestItems.value = []
      testPurpose.value = ''
      totalAmount.value = 0
    }
  } catch (error) {
    console.error('提交检验申请失败', error)
    ElNotification({
      title: '错误',
      message: `提交失败: ${error.response?.data?.message || '服务器错误'}`,
      type: 'error'
    })
  }
}

// 加载患者检验项目
const loadPatientTestItemsByRegisterId = async (registerId) => {
  if (!registerId) {
    selectedTestItems.value = []
    testPurpose.value = ''
    totalAmount.value = 0
    return
  }

  // 正确路径：/api/test-items/patient/register/${registerId}
  const loadPatientTestItemsByRegisterId = async (registerId) => {
    try {
      // 注意：后端接口是路径参数（/xxx/{registerId}），而非查询参数（?registerId=xxx）
      const res = await request.get(`/api/test-items/patient/register/${registerId}`);
      patientTestItems.value = res.data; // 后端返回的Checkapply列表
      console.log('患者检验项目加载成功', res.data);
    } catch (error) {
      console.error('加载患者检验项目失败', error);
    }
  };
}

// -------------------------- 门诊确诊功能 --------------------------
// 获取患者诊断信息
const fetchDiagnosisInfo = async (caseNumber) => {
  if (!caseNumber) {
    resetDiagnosisForm()
    return
  }

  diagnosisLoading.value = true
  try {
    const res = await service.get('/api/diagnosis', {
      params: { caseNumber }
    })

    if (res.data) {
      diagnosisInfo.value = res.data
      diagnosisConfirmed.value = res.data.confirmed
    } else {
      resetDiagnosisForm(caseNumber)
    }
  } catch (error) {
    console.error('加载诊断信息失败', error)
    ElNotification({
      title: '错误',
      message: '加载诊断信息失败，请重试',
      type: 'error'
    })
    resetDiagnosisForm(caseNumber)
  } finally {
    diagnosisLoading.value = false
  }
}

// 保存诊断（暂存）
const saveDiagnosis = async () => {
  if (!currentPatient.value) {
    ElNotification({
      title: '提示',
      message: '请先选择患者',
      type: 'warning'
    })
    return
  }

  if (!diagnosisInfo.value.mainDiagnosis) {
    ElNotification({
      title: '提示',
      message: '请填写主要诊断',
      type: 'warning'
    })
    return
  }

  try {
    const diagnosisData = {
      ...diagnosisInfo.value,
      caseNumber: currentPatient.value.caseNumber,
      registerId: currentPatient.value.registerId,
      doctorId: userId.value,
      confirmed: false
    }

    const res = await service.post('/api/diagnosis/save', diagnosisData)

    if (res.data.success) {
      ElNotification({
        title: '成功',
        message: '诊断信息已保存',
        type: 'success'
      })
      diagnosisInfo.value = res.data.data
    }
  } catch (error) {
    console.error('保存诊断信息失败', error)
    ElNotification({
      title: '错误',
      message: `保存失败: ${error.response?.data?.message || '服务器错误'}`,
      type: 'error'
    })
  }
}

// 确认诊断（提交）
const confirmDiagnosis = async () => {
  if (!currentPatient.value) {
    ElNotification({
      title: '提示',
      message: '请先选择患者',
      type: 'warning'
    })
    return
  }

  if (!diagnosisInfo.value.mainDiagnosis) {
    ElNotification({
      title: '提示',
      message: '请填写主要诊断',
      type: 'warning'
    })
    return
  }

  ElMessageBox.confirm(
      '确定要确认诊断吗？确认后将无法修改',
      '确认诊断',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      const diagnosisData = {
        ...diagnosisInfo.value,
        caseNumber: currentPatient.value.caseNumber,
        registerId: currentPatient.value.registerId,
        doctorId: userId.value,
        confirmed: true,
        confirmedTime: new Date().toISOString()
      }

      const res = await service.post('/api/diagnosis/confirm', diagnosisData)

      if (res.data.success) {
        ElNotification({
          title: '成功',
          message: '诊断已确认提交',
          type: 'success'
        })
        diagnosisInfo.value = res.data.data
        diagnosisConfirmed.value = true
        // 自动标记患者为已诊
        endRegister()
      }
    } catch (error) {
      console.error('确认诊断失败', error)
      ElNotification({
        title: '错误',
        message: `确认失败: ${error.response?.data?.message || '服务器错误'}`,
        type: 'error'
      })
    }
  }).catch(() => {
    // 取消确认
  })
}

// 重置诊断表单
const resetDiagnosisForm = (caseNumber = '') => {
  diagnosisInfo.value = {
    mainDiagnosis: '',
    diagnosisCode: '',
    secondaryDiagnosis: '',
    diagnosisBasis: '',
    treatmentPlan: '',
    medicalAdvice: '',
    followUpVisit: '',
    otherInstructions: '',
    caseNumber,
    confirmed: false,
    confirmedTime: ''
  }
  diagnosisConfirmed.value = false
}
</script>

<style scoped>
/* 可根据需要添加组件样式 */
.el-tabs__content {
  height: 100%;
  overflow: hidden;
}

.el-table {
  margin-bottom: 10px;
}

.el-form-item {
  margin-bottom: 15px;
}
</style>```